<template>
  <div class="app-container">
    <div class="top-bar">
      <div>
        <el-dropdown @command="handleCommand">
          <el-button type="primary" size="small">添加备货单</el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="store">按店铺添加</el-dropdown-item>
              <el-dropdown-item command="disposable">
                一键添加所有
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button
          :type="startLoading ? 'danger' : 'primary'"
          size="small"
          :loading="startLoading"
          :disabled="startLoading"
          @click="handleStart"
        >
          开始抢仓
        </el-button>
        <el-button
          v-show="startLoading"
          type="warning"
          size="small"
          @click="handleStop"
        >
          停止抢仓
        </el-button>
      </div>
      <el-button
        size="small"
        type="primary"
        :icon="CircleCheck"
        circle
        @click="successVisible = true"
      />
    </div>
    <div class="content">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="subPurchaseOrderSn" label="备货单号" />
        <el-table-column label="商品信息" width="400">
          <template v-slot="{ row }">
            <div class="product-wrap">
              <img :src="row.productSkcPicture" alt="img" />
              <div>
                <span>备货母单号：{{ row.originalPurchaseOrderSn }}</span>
                <span>商品名称：{{ row.productName }}</span>
                <span>SKC：{{ row.productSkcId }}</span>
                <span>货号：{{ '' }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="mallName" label="店铺来源">
          <template v-slot>
            <span>{{ mallName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="SKU信息" width="300">
          <template v-slot="{ row }">
            <div
              v-for="sku in row.skuQuantityDetailList"
              :key="sku.productSkuId"
              class="product-wrap"
            >
              <img :src="sku.thumbUrlList[0]" alt="img" />
              <div>
                <span>属性：{{ sku.className }}</span>
                <span>下单数量：{{ sku.purchaseQuantity }}</span>
                <span>SKU ID：{{ sku.productSkuId }}</span>
                <span>SKU 货号：{{ sku.goodsSkuId }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template v-slot="{ row }">
            <el-tag v-if="row.status === 1" type="warning">待发货</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <!--<el-table-column fixed="right" label="抢仓信息" width="150">-->
        <!--  <template v-slot="row">-->
        <!--    <p>-->
        <!--      已抢仓-->
        <!--      <el-tag type="danger">{{ row['__TM_times__'] }}</el-tag>-->
        <!--      次-->
        <!--    </p>-->
        <!--  </template>-->
        <!--</el-table-column>-->
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="removeRow(row)">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="dialogVisible" title="添加备货单" width="1200px">
      <div class="dialog-body">
        <div class="top-bar">
          <el-select
            v-model="value"
            placeholder="请选择 店铺"
            size="small"
            @change="selectMall"
          >
            <el-option
              v-for="item in mallList"
              :key="item.mallId"
              :label="item.mallName"
              :value="item.mallId"
            />
          </el-select>
        </div>
        <el-table
          ref="multipleTableRef"
          :data="mallOrderList"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="subPurchaseOrderSn" label="备货单号" />
          <el-table-column label="商品信息">
            <template v-slot="{ row }">
              <div class="product-wrap">
                <img :src="row.productSkcPicture" alt="img" />
                <div>
                  <span>备货母单号：{{ row.originalPurchaseOrderSn }}</span>
                  <span>商品名称：{{ row.productName }}</span>
                  <span>SKC：{{ row.productSkcId }}</span>
                  <span>货号：{{ '' }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="SKU信息">
            <template v-slot="{ row }">
              <div
                v-for="sku in row.skuQuantityDetailList"
                :key="sku.productSkuId"
                class="product-wrap"
              >
                <img :src="sku.thumbUrlList[0]" alt="img" />
                <div>
                  <span>属性：{{ sku.className }}</span>
                  <span>下单数量：{{ sku.purchaseQuantity }}</span>
                  <span>SKU ID：{{ sku.productSkuId }}</span>
                  <span>SKU 货号：{{ sku.goodsSkuId }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="addSelection"> 添加 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="successVisible" title="抢单成功列表" width="1200px">
      <div class="dialog-body">
        <div class="top-bar">
          <el-select
            v-model="successMall"
            placeholder="请选择 店铺"
            size="small"
            @change="selectMall"
          >
            <el-option
              v-for="item in mallList"
              :key="item.mallId"
              :label="item.mallName"
              :value="item.mallId"
            />
          </el-select>
        </div>
        <el-table
          ref="multipleTableRef"
          :data="successList"
          border
          style="width: 100%"
        >
          <el-table-column prop="subPurchaseOrderSn" label="备货单号" />
          <el-table-column prop="subPurchaseOrderSn" label="店铺来源" />
          <el-table-column prop="subPurchaseOrderSn" label="商品名称" />
          <el-table-column prop="subPurchaseOrderSn" label="货号" />
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="successVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { getAllSubOrderList } from '@/api/pdd'
import { useUserStore } from '@/store/user'
import { ElMessage as message } from 'element-plus'
import { CircleCheck } from '@element-plus/icons-vue'
import { batchRob, stopRob } from '@/api/user'

const userStore = useUserStore()
const mallList = computed(() => {
  if (userStore.userInfo?.companyList && userStore.userInfo?.companyList[0]) {
    return userStore.userInfo.companyList[0].malInfoList
  } else {
    return []
  }
})
const tableData = ref([])
const dialogVisible = ref(false)
const value = ref('')
const mallOrderList = ref([])
const startLoading = ref(false)
const successList = ref([])
const execSwitch = ref(false)
const successVisible = ref(false)
const successMall = ref('')

const mallName = computed(() => {
  let item = mallList.find((mall) => mall.mallId == value.value)
  return item.mallName || 'Null'
})

const handleCommand = (e) => {
  if (userStore.sysUser.user_level === 0) {
    return message.error('请激活账号，才可使用此功能')
  }
  if (
    userStore.sysUser.user_level === 1 &&
    userStore.sysUser.boundled_mallShops.length === 0
  ) {
    return message.error('请先绑定店铺')
  }
  if (e === 'disposable') {
    // TODO
    return selectMall('')
  }
  dialogVisible.value = true
}
const handleStart = () => {
  if (tableData.value.length === 0) return message.error('请先添加备货单！')
  execSwitch.value = true
  startLoading.value = true
  loopExec()
}
const handleStop = () => {
  startLoading.value = false
  execSwitch.value = false
}
const selectMall = async (val) => {
  userStore.$patch({
    currentMall: val
  })
  const { result } = await getAllSubOrderList({
    isCustomGoods: false,
    pageNo: 1,
    pageSize: 100,
    statusList: [1],
    urgencyType: 0
  })
  mallOrderList.value = result.subOrderForSupplierList
}
const multipleTableRef = ref()
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const addSelection = () => {
  tableData.value = [...multipleSelection.value]
  dialogVisible.value = false
}
const removeRow = (row) => {
  tableData.value = tableData.value.filter((r) => r !== row)
}

// 抢仓相关
const handleOccupy = () => {
  const rob_lists = tableData.value.map((row) => row.subPurchaseOrderSn)
  batchRob({ rob_lists }).then((res) => {
    successList.value = res.success_rob_lists
  })
}
const sleep = (time) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, time)
  })
}
const loopExec = async () => {
  let time = Math.round(1000 + Math.random() * 8000)
  handleOccupy()
  await sleep(time)
  execSwitch.value && (await loopExec())
}
</script>

<style scoped lang="scss">
.app-container {
  margin: 20px;
  padding: 20px;
  background-color: #fff;
}
.top-bar {
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
}
:deep(.top-bar .el-dropdown) {
  margin-right: 12px;
}

.product-wrap {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  > img {
    width: 60px;
    height: 60px;
    flex-shrink: 0;
  }
  > div {
    display: flex;
    flex: 1;
    width: 100%;
    overflow: hidden;
    flex-direction: column;
    justify-content: center;
    padding: 0 12px;
    > span {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
